package ahblue.cn.tanzi.ui.circle;

import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.github.kimkevin.cachepot.CachePot;
import com.rhino.dialog.BottomSelectDialogFragment;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.shehuan.nicedialog.BaseNiceDialog;
import com.shehuan.nicedialog.NiceDialog;
import com.shehuan.nicedialog.ViewConvertListener;
import com.shehuan.nicedialog.ViewHolder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import ahblue.cn.tanzi.R;
import ahblue.cn.tanzi.data.Result;
import ahblue.cn.tanzi.data.source.ApiCallback;
import ahblue.cn.tanzi.data.source.RemoteRepository;
import ahblue.cn.tanzi.model.circle.Circle;
import ahblue.cn.tanzi.model.circle.CircleDynamicItem;
import ahblue.cn.tanzi.model.user.LoginResultModel;
import ahblue.cn.tanzi.ui.base.BaseFragment;
import ahblue.cn.tanzi.ui.common.UIConfig;
import ahblue.cn.tanzi.ui.dialog.DialogFactory;
import ahblue.cn.tanzi.ui.home.search.SearchActivity;
import ahblue.cn.tanzi.ui.person.MemberInfoActivity;
import ahblue.cn.tanzi.util.GlideApp;
import ahblue.cn.tanzi.util.TimeUtils;
import ahblue.cn.tanzi.view.ImageNineGridView;
import ahblue.cn.tanzi.view.MyLinearLayoutManager;
import ahblue.cn.tanzi.view.video.MediaPlayer;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

import static android.app.Activity.RESULT_OK;

/**
 * 圈子首页
 */
public class CircleFragment extends BaseFragment {

    private static final int CODE_TO_START = 0x001;
    private static final int CODE_TO_END = 0x002;

    @BindView(R.id.recyclerViewCircleList)
    RecyclerView mRecyclerViewCircleList;
    @BindView(R.id.recyclerViewCircleMovement)
    RecyclerView mRecyclerViewCircleMovement;
    @BindView(R.id.tv_title)
    TextView mTextViewTitle;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    // 搜索
    @BindView(R.id.tv_search)
    TextView mTextViewSearch;
    @BindView(R.id.sv_circle_fragment_content)
    ScrollView scCircleFragmentContent;



    private LoginResultModel mLoginResultModel;

    // 动态广场
    private int mDynamicPage = 0;
    private static final int DYNAMIC_PAGECOUNT = 3;

    private List<CircleDynamicItem> mDynamicList = new ArrayList<>();
    private CircleMovementAdapter mDynamicAdapter;

    private boolean mIsDynamicRefresh;
    private boolean mIsDynamicLoadMore;
    //标识是否滑动到顶部
    private boolean isScrollToStart = false;
    //标识是否滑动到底部
    private boolean isScrollToEnd = false;
    //动态广场是否滑到了顶部
    private boolean rvIsScrollTop = false;
    private MyLinearLayoutManager myLinearLayoutManager;

    private boolean isActionDown = true;


    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CODE_TO_START:
                    //重置标志“滑动到顶部”时的标志位
                    isScrollToStart = false;
                    break;
                case CODE_TO_END:
                    //重置标志“滑动到底部”时的标志位
                    isScrollToEnd = false;
                    break;
                default:
                    break;
            }
        }
    };


    public CircleFragment() {
        // Required empty public constructor
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_circle, container, false);
        ButterKnife.bind(this, view);

        initData();
        initView();

        return view;
    }

    private void initData() {
        mLoginResultModel = LoginResultModel.getUserModel(getContext(), LoginResultModel.class);

        RemoteRepository repo = RemoteRepository.getsInstance();

        // 获取圈子顶部五个动态圈子
        Disposable d = repo.getCircleTop(mCallbackCircleTop);
        addRxDisposable(d);

        mDynamicPage = 0;
        loadDynamic4Page(mDynamicPage);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() {
        mTextViewTitle.setText("圈子");

        mTextViewSearch.setText(R.string.circle_search_hint);

        mDynamicAdapter = new CircleMovementAdapter(mDynamicList);
        mDynamicAdapter.setOnItemClickListener(mMovementItemClickListener);
        mDynamicAdapter.setOnItemChildClickListener(mMovementItemChildClickListener);

        myLinearLayoutManager = new MyLinearLayoutManager(getActivity());
        myLinearLayoutManager.setScrollEnabled(false);
        mRecyclerViewCircleMovement.setLayoutManager(myLinearLayoutManager);
        mRecyclerViewCircleMovement.setAdapter(mDynamicAdapter);

        mRefreshLayout.setOnRefreshListener(refreshlayout -> {
            mDynamicPage = 0;
            mDynamicList.clear();
            mIsDynamicRefresh = true;

            loadDynamic4Page(mDynamicPage);
        });
        mRefreshLayout.setOnLoadmoreListener(refreshlayout -> {
            scCircleFragmentContent.requestDisallowInterceptTouchEvent(true);
            mDynamicPage += 1;
            mIsDynamicLoadMore = true;

            loadDynamic4Page(mDynamicPage);
        });

        scCircleFragmentContent.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                Log.e("kzg","*********************************rvIsScrollTop:"+rvIsScrollTop);
                if (!rvIsScrollTop){
                    myLinearLayoutManager.setScrollEnabled(true);

                }

                //获取最上面的那个view是否可见
                boolean isVisible = mRecyclerViewCircleList.getLocalVisibleRect(new Rect());
                //滚动到顶部，ScrollView存在回弹效果效应（这里只会调用两次，如果用<=0,会多次触发）
                if (scCircleFragmentContent.getScrollY() == 0 && isVisible) {
                    myLinearLayoutManager.setScrollEnabled(false);
                    Log.e("kzg","*********************************toStart");
                    isScrollToStart = true;
                    mRefreshLayout.autoRefresh();
                } else {
                    View contentView = scCircleFragmentContent.getChildAt(0);
                    if (contentView != null && contentView.getMeasuredHeight() == (scCircleFragmentContent.getScrollY() + scCircleFragmentContent.getHeight())) {
                        //滚动到底部，ScrollView存在回弹效果效应
                        isScrollToEnd = true;
                        Log.e("kzg","*********************************toEnd");
                        myLinearLayoutManager.setScrollEnabled(true);
                        mRefreshLayout.autoLoadmore();

                    }else {
                        isScrollToEnd = false;
                        isScrollToStart = false;
                    }

                }
            }
        });

/*        final float[] y = {0};
        scCircleFragmentContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (isActionDown){
                    y[0] = event.getY();
                }
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        break;
                    case MotionEvent.ACTION_MOVE:
                        isActionDown = false;
                        float y2 = event.getY();
                        Log.e("kzg","*********************************y2-y:" +(y2 - y[0]));
                        if ((y2 - y[0]) > 50 && isScrollToStart && rvIsScrollTop){
                            //往下滑
                            myLinearLayoutManager.setScrollEnabled(true);
                            return false;
                        }else if ((y2 - y[0]) <= 50 && isScrollToStart && rvIsScrollTop){
                            myLinearLayoutManager.setScrollEnabled(false);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        isActionDown = true;
                        y[0] = 0;
                        break;
                }

                return isScrollToStart && rvIsScrollTop;
            }
        });*/

        mRecyclerViewCircleMovement.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                super.onScrolled(recyclerView, dx, dy);
                if(mRecyclerViewCircleMovement.canScrollVertically(1)){

                }else {
                    Log.e("kzg","*********************************mRecyclerViewCircleMovement-end");
                    //滑动到底部
                    mRefreshLayout.autoLoadmore();
                }
                if(mRecyclerViewCircleMovement.canScrollVertically(-1)){
                    rvIsScrollTop = false;
                }else {
                    Log.e("kzg","*********************************mRecyclerViewCircleMovement-start");
                    //滑动到顶部
                    rvIsScrollTop = true;
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == UIConfig.REQ_CODE_ADD_DYNAMIC) {
            if (resultCode == RESULT_OK) {
                mDynamicPage = 0;
                mDynamicList.clear();
                loadDynamic4Page(mDynamicPage);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 加载指定页码的动态。
     * @param page 页码
     */
    private void loadDynamic4Page(int page) {
        RemoteRepository repo = RemoteRepository.getsInstance();
        Disposable d = repo.getBigShotUserDynamic(page, DYNAMIC_PAGECOUNT, "", mLoginResultModel.token, mCallbackCircleMovementItem);
        addRxDisposable(d);
    }

    /**
     * 圈子顶部接口回调
     */
    ApiCallback<List<Circle>> mCallbackCircleTop = new ApiCallback<List<Circle>>() {
        @Override
        public void onSuccess(List<Circle> data) {
            Circle c = new Circle();
            c.fake_tag = 1999;
            data.add(c);

            CircleHeadAdapter adapter = new CircleHeadAdapter(data);
            adapter.setOnItemClickListener(mCircleItemClickListener);

            mRecyclerViewCircleList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
            mRecyclerViewCircleList.setAdapter(adapter);
        }

        @Override
        public void onFailed(String errorMsg) {

        }
    };

    /**
     * 动态广场回调
     */
    ApiCallback<List<CircleDynamicItem>> mCallbackCircleMovementItem = new ApiCallback<List<CircleDynamicItem>>() {
        @Override
        public void onSuccess(List<CircleDynamicItem> data) {
            mDynamicList.addAll(data);
            mDynamicAdapter.notifyDataSetChanged();

            if (mIsDynamicRefresh) {
                mIsDynamicRefresh = false;
                mRefreshLayout.finishRefresh(true);
            }

            if (mIsDynamicLoadMore) {
                mIsDynamicLoadMore = false;
                mRefreshLayout.finishLoadmore(true);
            }

        }

        @Override
        public void onFailed(String errorMsg) {
            if (mIsDynamicRefresh) {
                mIsDynamicRefresh = false;
                mRefreshLayout.finishRefresh(false);
            }

            if (mIsDynamicLoadMore) {
                mIsDynamicLoadMore = false;
                mRefreshLayout.finishLoadmore(false);
            }
        }
    };

    /**
     * 页面顶部推荐圈子的单击事件处理
     */
    BaseQuickAdapter.OnItemClickListener mCircleItemClickListener = (adapter, view, position) -> {
        Circle circle = (Circle) adapter.getData().get(position);
        if (circle == null)
            return;

        Intent intent;
        if (circle.fake_tag == 1999) {
            intent = new Intent(CircleFragment.this.getActivity(), CircleShowAllActivity.class);
        } else {
            intent = new Intent(CircleFragment.this.getActivity(), CircleDetailActivity.class);
            intent.putExtra(CircleDetailActivity.ARG_CIRCLE_ID, circle.id);
        }

        CircleFragment.this.startActivity(intent);
    };

    /**
     * 动态单击事件处理
     */
    BaseQuickAdapter.OnItemClickListener mMovementItemClickListener = (adapter, view, position) -> {
        CircleDynamicItem item = (CircleDynamicItem) adapter.getItem(position);
        openDynamicDetail(item);
    };

    /**
     * 处理动态点赞和取消点赞的操作
     * @param data 需要处理的动态
     */
    private void handleFabulous(@NonNull CircleDynamicItem data, TextView view) {
        RemoteRepository repo = RemoteRepository.getsInstance();
        if (data.is_fabulous == 0) {
            Disposable d = repo.addBigShotDynamicToFabulous(data.id, mLoginResultModel.token, new ApiCallback<Result>() {
                @Override
                public void onSuccess(Result result) {
                    data.is_fabulous = 1;
                    data.fabulous_count += 1;
                    setFabulousState(data, view);
                }

                @Override
                public void onFailed(String errorMsg) {

                }
            });
            addRxDisposable(d);
        } else {
            Disposable d = repo.deleteBigShotArticleDeleteDynamicFabulous(data.id, mLoginResultModel.token, new ApiCallback<Result>() {
                @Override
                public void onSuccess(Result result) {
                    data.is_fabulous = 0;
                    data.fabulous_count -= 1;
                    setFabulousState(data, view);
                }

                @Override
                public void onFailed(String errorMsg) {

                }
            });
            addRxDisposable(d);
        }
    }

    private void openDynamicDetail(CircleDynamicItem item) {
        if (item == null)
            return;

        CachePot.getInstance().push(item);
        final Intent intent = new Intent(CircleFragment.this.getActivity(), DynamicDetailActivity.class);
        Log.e("kzg","***************************item:"+item.id);
        CircleFragment.this.startActivity(intent);
    }

    private void setFabulousState(CircleDynamicItem item, TextView view) {
        int imgId = item.is_fabulous != 0 ? R.drawable.dynamic_icon_like_s : R.drawable.dynamic_icon_like_n;
        Drawable drawable = getResources().getDrawable(imgId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        view.setCompoundDrawables(drawable, null, null, null);

        view.setText(Integer.toString(item.fabulous_count));
    }


    private BaseQuickAdapter.OnItemChildClickListener mMovementItemChildClickListener = new BaseQuickAdapter.OnItemChildClickListener() {
        @Override
        public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
            CircleDynamicItem item = (CircleDynamicItem) adapter.getData().get(position);
            long userId = item.user_id;

            int viewId = view.getId();
            switch (viewId) {
                case R.id.iv_circle_home_img:
                case R.id.tv_dynamic_bottom_from:
                    Intent infoIntent = new Intent(CircleFragment.this.getActivity(), MemberInfoActivity.class);
                    infoIntent.putExtra(MemberInfoActivity.ARG_USER_ID, userId);
                    CircleFragment.this.startActivity(infoIntent);
                    break;

                case R.id.tv_dynamic_bottom_comment:
                    openDynamicDetail(item);
                    break;

                case R.id.tv_dynamic_bottom_like:
                    handleFabulous(item, (TextView) view);
                    break;

                case R.id.tv_dynamic_share:
                    break;
            }
        }
    };

    // 单击“发布”
    @OnClick(R.id.ll_fabu)
    void onClickButtonRight() {
        DialogFactory.showCircleFabuDialog(getActivity(), new BottomSelectDialogFragment.IOnItemClickListener() {
            @Override
            public void onItemClick(BottomSelectDialogFragment dialog, BottomSelectDialogFragment.Item item) {
                dialog.dismiss();
                if ("文字".equals(item.mText)) {
                    final Intent intent = new Intent(CircleFragment.this.getContext(), IssueDynamicTextActivity.class);
                    CircleFragment.this.startActivityForResult(intent, UIConfig.REQ_CODE_ADD_DYNAMIC);
                } else if ("图片".equals(item.mText)) {
                    final Intent intent = new Intent(CircleFragment.this.getContext(), IssueDynamicImageActivity.class);
                    CircleFragment.this.startActivityForResult(intent, UIConfig.REQ_CODE_ADD_DYNAMIC);
                } else if ("视频".equals(item.mText)) {
                    final Intent intent = new Intent(CircleFragment.this.getContext(), IssueDynamicVideoActivity.class);
                    CircleFragment.this.startActivityForResult(intent, UIConfig.REQ_CODE_ADD_DYNAMIC);
                }
            }
        });
    }

    // 单击"我的圈子"
    @OnClick(R.id.rl_circlehome_mycircle)
    void onClickMyCircle() {
        LoginResultModel loginResultModel = LoginResultModel.getUserModel(getContext(), LoginResultModel.class);
        if (loginResultModel == null)
            return;

        Intent intent;
        if (loginResultModel.circle_id.size() == 0) {
            // 没有圈子
            intent = new Intent(getActivity(), CircleMyselfNullActivity.class);
        } else {
            intent = new Intent(getActivity(), CircleMyselfActivity.class);
        }

        startActivity(intent);
    }

    // 单击圈子排行
    @OnClick(R.id.ll_circlehome_ranking)
    void onClickRanking() {
        final Intent intent = new Intent(getActivity(), CircleToplistActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.layout_search)
    void onClickSearch() {
        final Intent intent = new Intent(getActivity(), SearchActivity.class);
        startActivity(intent);
    }

    /**
     * 推荐圈子列表的adapter。
     */
    class CircleHeadAdapter extends BaseQuickAdapter<Circle, BaseViewHolder> {

        CircleHeadAdapter(@Nullable List<Circle> data) {
            super(R.layout.item_circle_home_circles, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, Circle item) {
            ImageView imgView = helper.getView(R.id.iv_circles_pic);
            helper.setVisible(R.id.tv_circles_all, false);
            helper.setVisible(R.id.iv_circles_pic, true);
            helper.setVisible(R.id.tv_circles_title, true);
            if (item.fake_tag == 1999) {
                helper.setVisible(R.id.tv_circles_all, true);
                helper.setVisible(R.id.iv_circles_pic, false);
                helper.setVisible(R.id.tv_circles_title, false);
//                imgView.setImageResource(R.drawable.icon_dynamic_share);
            } else {
                helper.setText(R.id.tv_circles_title, item.circle_name);
                GlideApp.with(imgView).load(item.head_portrait)
                        .placeholder(R.drawable.user_default_avatar)
                        .error(R.drawable.user_default_avatar)
                        .into(imgView);
            }
        }
    }

    /**
     * 动态广场列表的adapter。
     */
    class CircleMovementAdapter extends BaseQuickAdapter<CircleDynamicItem, BaseViewHolder> {

        CircleMovementAdapter(@Nullable List<CircleDynamicItem> data) {
            super(R.layout.item_circle_home_threeimgv5, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, CircleDynamicItem item) {
            TextView textView = helper.getView(R.id.tv_circle_home_three_content);
            TextView tvShowMore = helper.getView(R.id.tv_chakanquanbu);
            ImageView iv = helper.getView(R.id.iv_circle_home_img);
            GlideApp.with(iv).load(item.member_avatar)
                    .placeholder(R.drawable.user_default_avatar)
                    .error(R.drawable.user_default_avatar)
                    .into(iv);

            helper.setText(R.id.tv_circle_home_name, item.member_name);
            helper.setText(R.id.tv_circle_home_three_content, item.content);
            helper.setText(R.id.tv_circle_home_time, TimeUtils.getStandardDate(item.add_time));

            ImageNineGridView gv = helper.getView(R.id.img_grid_layout);
            MediaPlayer player = helper.getView(R.id.ic_player);

            gv.setVisibility(View.GONE);
            player.setVisibility(View.GONE);

            if (item.is_movie == 0) {
                if (item.pic.length != 0) {
                    List<String> imgUriList = Arrays.asList(item.pic);
                    gv.render(imgUriList);

                    gv.setVisibility(View.VISIBLE);
                }
            } else {
                player.setVisibility(View.VISIBLE);
                player.setVideoPath(item.movie_file, CircleFragment.this.getActivity());
            }

            TextView textViewFabulous = helper.getView(R.id.tv_dynamic_bottom_like);
            setFabulousState(item, textViewFabulous);

            helper.setText(R.id.tv_dynamic_bottom_like, Integer.toString(item.fabulous_count));
            helper.setText(R.id.tv_dynamic_bottom_comment, Integer.toString(item.comment_count));

            helper.addOnClickListener(R.id.iv_circle_home_img);
            helper.addOnClickListener(R.id.tv_dynamic_bottom_from);
            helper.addOnClickListener(R.id.tv_dynamic_bottom_comment);
            helper.addOnClickListener(R.id.tv_dynamic_bottom_like);
            helper.addOnClickListener(R.id.tv_dynamic_share);

            textView.post(new Runnable() {
                @Override
                public void run() {
                    if (textView.getLineCount() > 3) {
                        textView.setMaxLines(3);
                        tvShowMore.setVisibility(View.VISIBLE);
                    } else {
                        tvShowMore.setVisibility(View.GONE);
                    }
                }
            });

            helper.getView(R.id.tv_chakanquanbu).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if ("收起".equals(tvShowMore.getText().toString())) {
                        textView.setEllipsize(TextUtils.TruncateAt.END);//收起
                        textView.setLines(3);
                        tvShowMore.setText("全文");
                    } else {
                        textView.setEllipsize(null);//展开
                        textView.setSingleLine(false);//这个方法是必须设置的，否则无法展开
                        tvShowMore.setText("收起");
                    }
                }
            });
        }
    }

}
